package com.leyou.seckill.controller;

import com.leyou.seckill.mapper.SeckillMapper;
import com.leyou.seckill.pojo.SeckillItem;
import com.leyou.seckill.service.SeckillService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀Controller
 *
 * @author RudolfHugh
 * @since 2020/5/29 17:45
 */
@RestController
public class SeckillController implements InitializingBean {

  @Autowired private SeckillService seckillService;

  @Autowired private StringRedisTemplate stringRedisTemplate;

  @Autowired private SeckillMapper seckillMapper;

  /**
   * 系统初始化，初始化秒杀商品数量
   *
   * @throws Exception
   */
  @Override
  public void afterPropertiesSet() throws Exception {

    SeckillItem seckillItem = new SeckillItem();
    seckillItem.setEnable(true);
    List<SeckillItem> seckillItemList = seckillMapper.select(seckillItem);

    // 提前将秒杀商品信息存进Redis,并设置过期时间,后期就可以incr
    seckillItemList.forEach(
        seckillItemData -> {
          ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
          operations.set(
              seckillItemData.getSkuId().toString(),
              seckillItemData.getStock().toString(),
              seckillItemData.getEndTime().getTime() - seckillItemData.getStartTime().getTime(),
              TimeUnit.MILLISECONDS);
        });
  }

  /**
   * 秒杀功能
   *
   * @return
   */
  @PostMapping("/seckill/{skuId}")
  public ResponseEntity<String> seckillOrder(@PathVariable("skuId") Long skuId) {
    return seckillService.seckillItem(skuId);
  }
}
